<template>
  <div id="knowCatalogManageDiv">
    <Splitpanes>
      <Pane size="25">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeloading" @click="findKnowledgeCatalogAndContentTree"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建目录" :disabled="isAddCatalogFlag" v-if="!isAddCatalogFlag" @click="addCatalogDialog()"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建标题" :disabled="isAddContentFlag" v-if="!isAddContentFlag"
              @click="addCatalogContentDialog()"></vxe-button>
          </template>
        </vxe-toolbar>

        <el-scrollbar style="height: calc(100% - 40px)">
          <div class="sampleType">
            <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="catalogDataTree" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree" @node-click="handleClickType"
              v-loading="treeloading">
              <template #default="{ data, node }">
                <span><img :src="'../../../src/assets/images/Knowledge/' + data.knType + '.png'" style="width: 15px; height: 15px; margin-right: 10px" />
                  <div style="float: right">
                    {{ data.name }}
                  </div>
                </span>
                <div>
                  <span>
                    <!-- 新增  -->
                    <el-button type="success" class="cirBtn" size="small" icon="Plus" circle v-if="data.knType!='content'" @click="appendCatalogOrContent(data)"></el-button>
                    <!-- 编辑  -->
                    <el-button type="warning" class="cirBtn" size="small" icon="Edit" circle v-if="data.knType=='catalog'||(data.knType=='content'&&data.status<5)"
                      @click="editCatalogOrContent(data, node)"></el-button>
                    <!-- 删除  -->
                    <el-button type="info" class="cirBtn" size="small" icon="Delete" circle v-if="data.knType=='catalog'||(data.knType=='content'&&data.status<5)"
                      @click="removeCatalogOrContent(data)"></el-button>
                  </span>
                </div>
              </template>
            </el-tree>
          </div>
        </el-scrollbar>
      </Pane>

      <Pane size="75">
        <div class="cardBox" v-loading="conloading" element-loading-text="富文本加载中，请耐心等待..." element-loading-spinner="el-icon-loading">
          <!-- <el-scrollbar style="height: 100%;"> -->
            <div class="item-interval" v-if="!isEmpty(sltContent)">
              <el-divider content-position="left" class="el-divider-title">
                {{ sltContent.title + '（'}}{{  getContentStatusDesc(sltContent) }}{{'）'}}

                <vxe-button v-if="sltContent.status==10||sltContent.status==11||sltContent.status==20" @click="editTempContentDialog(sltContent)" type="text" status="primary" content="修改"
                  icon="vxe-icon-edit"></vxe-button>
                <!-- <vxe-button
                  @click="handleEditGroupContent(sltContent)"
                  type="text"
                  status="primary"
                  icon="vxe-icon-fullscreen"></vxe-button> -->

                <vxe-button v-if="sltContent.status<5" @click="deleteContent(sltContent)" type="text" status="primary" icon="vxe-icon-delete"></vxe-button>
              </el-divider>

              <CkEditor ref="refContentCkEditor" :folderId="sltCatalog.id" @editor-input="(val)=>sltContent.status<10? sltContent.tempContent=val:sltContent.content=val" />
              <div class="save-footer">
                <vxe-button type="text" class="button-blue" icon="vxe-icon-save" v-if="sltContent.status<5" content="暂存" @click="updateContent"></vxe-button>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-send" v-if="sltContent.status<5" content="提交" @click="submitContent"></vxe-button>
              </div>
              <el-tabs type="border-card" v-model="activeName" :class="sltContent.status < 5 ? 'showTwoButtonTabs' : 'alreadySubmitTabs' " @tab-click="tabHandleClick">
                <el-tab-pane label="问题" name="issueTab">
                  <div class="tabTableBox">
                    <vxe-table :data="sltContent.wkKnowledgeIssueList" :loading="isLoading" class="mytable-scrollbar" height="auto">
                      <vxe-column type="seq" title="序号" width="60"></vxe-column>
                      <vxe-column field="title" title="问题">
                        <template #default="{ row }">
                          {{row.title}}

                          <el-popover placement="right" :width="200" trigger="hover">
                            <div v-html="row.solution">
                            </div>
                            <template #reference>
                              <el-link icon="view" size="default" type="primary" style="margin-left:10px">查看解决方案</el-link>
                            </template>
                          </el-popover>

                        </template>
                      </vxe-column>

                      <vxe-column title="操作" fixed="right" width="100">
                        <template #header>
                          <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAddIssue()"></vxe-button>
                        </template>
                        <template #default="{ row,rowIndex }">
                          <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click.native="handleEditIssue(row,rowIndex)" class="spanIcon"></vxe-button>
                          <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="handleDeleteIssue(row.id,rowIndex,sltContent.wkKnowledgeIssueList)"
                            class="spanIcon"></vxe-button>
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="修改记录" name="approvalTab">
                  <el-scrollbar>
                    <KnowledgeApprovalList ref="approvalListRef" />
                  </el-scrollbar>
                </el-tab-pane>

                <el-tab-pane label="知识库试题" name="approvalTab2">
                  <KnowledgeTests  ref="KnowledgeTestsRef"/>
                </el-tab-pane>
              </el-tabs>

            </div>
          <!-- </el-scrollbar> -->
        </div>
      </Pane>
    </Splitpanes>

    <el-dialog :title="titleCatalog()" :show-close="false" v-model="showCatalogDialog" append-to-body :close-on-click-modal="false" width="500px">
      <el-form ref="catalogFormRef" :model="catalogForm" :rules="catalogFormRule" label-width="100px" class="form-input-m" inline-message>
        <el-form-item prop="pname" label="父级目录" v-if="pnameShow">
          <el-input type="text" v-model="catalogForm.pname" placeholder="请输入父类名称" disabled></el-input>
        </el-form-item>
        <el-form-item prop="code" label="编号">
          <el-input type="text" v-model="catalogForm.code" placeholder="请输入字典编号" clearable></el-input>
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input type="text" v-model="catalogForm.name" placeholder="请输入字典名称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="catalogForm.status" placeholder="请选择状态">
            <el-option v-for="status in statusTypes" :key="status.code" :label="status.name" :value="status.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="seq" label="排序" class="input-s">
          <el-input-number v-model="catalogForm.seq" :min="0" :max="100" label="请输入顺序号"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer flex right justify-end">
        <el-button type="primary" @click="saveCatalog('catalogFormRef')">保存</el-button>
        <el-button @click="closeCatalogDialog('catalogFormRef')">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleContent()" :show-close="false" v-model="showContentDialog" append-to-body :close-on-click-modal="false" width="500px">
      <el-form ref="contentFormRef" :model="contentForm" :rules="contentFormRule" label-width="100px" class="form-input-m" inline-message>
        <el-form-item prop="title" label="标题">
          <el-input type="text" v-model="contentForm.title" placeholder="请输入标题" clearable></el-input>
        </el-form-item>
        <el-form-item prop="publishTime" label="发布时间">
          <el-date-picker v-model="contentForm.publishTime" type="datetime" placeholder="请选择发布时间"></el-date-picker>
        </el-form-item>
        <el-form-item prop="seq" label="排序" class="input-s">
          <el-input-number v-model="contentForm.seq" :min="0" :max="100" label="请输入顺序号"></el-input-number>
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex right justify-end">
        <el-button type="primary" @click="saveContent('contentFormRef')">保存</el-button>
        <el-button @click="closeContentDialog('contentFormRef')">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="知识库问题" :show-close="false" v-model="showIssueDialog" :append-to-body="true" :close-on-click-modal="false" width="800px">
      <el-form ref="issueFormRef" :model="issueForm" :rules="issueFormRule" label-width="80px" class="form-input-l" :inline-message="true">
        <el-form-item prop="title" label="问题标题">
          <el-input type="text" v-model="issueForm.title" placeholder="请输入标题" clearable style="width:700px"></el-input>
        </el-form-item>
        <el-form-item prop="solution" label="解决方案">
          <CkEditor ref="refIssueEditor" :folderId="issueForm.catalogId" @editorInput="(val)=>issueForm.solution=val" style="width:700px" />
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex justify-end">
        <el-button type="primary" @click="confirmIssueForm('issueFormRef')">确定</el-button>
        <el-button @click="closeIssueDialog('issueFormRef')">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改" :show-close="false" v-model="showTempContentDialog" append-to-body :close-on-click-modal="false" width="800px">
      <el-form ref="tempContentFormRef" :model="contentForm" :rules="contentFormRule" label-width="100px" class="form-input-m" inline-message>
        <el-form-item prop="title" label="标题">
          <el-input type="text" v-model="contentForm.title" placeholder="请输入标题" clearable style="width:700px"></el-input>
        </el-form-item>
        <el-form-item prop="tempContent" label="内容">
          <CkEditor ref="refTempContentCkEditor" :folderId="contentForm.id" @editor-input="(val)=>contentForm.tempContent=val" style="width:700px" />
        </el-form-item>

      </el-form>
      <div class="dialog-footer flex right justify-end">
        <el-button type="primary" @click="submitTempContent('tempContentFormRef')">提交</el-button>
        <el-button @click="closeTempContentDialog('tempContentFormRef')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import CkEditor from '@/components/CkEditor.vue';
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import KnowledgeApprovalList from './KnowledgeApprovalList.vue';//修改记录
import KnowledgeTests from './KnowledgeTests.vue';//知识库试题
import { formatDateTime } from '@/utils/common'; //失控记录图表

let store = AppStore();
let { proxy }: any = getCurrentInstance();

defineExpose({ initPage });

let sltknowledge: any = {};
let treeloading = ref(false); //字典分类树上的刷新
let conloading = ref(false);
let isLoading = ref(false);
let catalogDataTree: any = reactive([]); //最左侧质控靶值设定树数据
let sltCatalog: any = {};
let sltContent: any = ref({});
let testQuestionList: any = reactive([]);
let pnameShow = ref(false); //父级分类显示
let showCatalogDialog = ref(false);
let showContentDialog = ref(false);
let showTempContentDialog = ref(false);
let approvalListRef: any = ref(null);//修改记录页签标记
let KnowledgeTestsRef:any = ref(null)//知识库试题页签标记
let isAddCatalogFlag = ref(true);
let isAddContentFlag = ref(true);

let showIssueDialog = ref(false);
let activeName = ref('issueTab');

let maxLevel = 2;

let statusTypes = [
  {
    name: '启用',
    code: true
  },
  {
    name: '禁用',
    code: false
  }
];

let catalogForm = reactive({
  id: null,
  knowledgeId: null,
  pname: '',
  pid: null,
  orgId: '',
  code: '',
  name: '',
  seq: 1,
  status: true
});

let catalogFormRule = {
  name: [
    {
      required: true,
      message: '请输入字典名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let contentForm = reactive({
  idx: null,
  id: null,
  knowledgeId: null,
  catalogId: null,
  orgId: '',
  title: '',
  content: '',
  tempContent: '',
  seq: 1,
  status: 0,
  publishTime: ''
});

let contentFormRule = {
  title: [
    {
      required: true,
      message: '请输入字典名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let issueForm = reactive({
  issueIdx: 0,
  id: null,
  knowledgeId: null,
  catalogId: null,
  contentId: null,
  orgId: '',
  title: '',
  solution: '',
  seq: 1,
  status: 0,
  publishTime: ''
});

let issueFormRule = {
  title: [
    {
      required: true,
      message: '请输入字典名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

function initPage(row: any) {
  sltknowledge = row;
  findKnowledgeCatalogAndContentTree('');
  KnowledgeTestsRef.value?.findTestQuestionList()
}
function findKnowledgeCatalogAndContentTree(sltId: any) {
  treeloading.value = true;
  catalogDataTree.length = 0;
  if (isEmpty(sltknowledge)) {
    treeloading.value = false;
    return;
  }

  const url = '/api/wk/wkKnowledgeCatalog/findKnowledgeCatalogAndContentTree';

  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { knowledgeId: sltknowledge.id } })
    .then((res: any) => {
      catalogDataTree.push({
        id: sltknowledge.id,
        name: sltknowledge.name,
        code: sltknowledge.code,
        knType: 'knowledge',
        level: 0,
        children: []
      });
      catalogDataTree[0].children.push(...res.data);
      if (catalogDataTree.length > 0) {
        const sltObj = getChildren(catalogDataTree[0], sltId);
        sltCatalog = sltObj;
        setCurTypeNode(sltObj.id);
        if (sltCatalog.knType == 'content') {
          getContentByContentId();
          KnowledgeTestsRef.value?.findTestQuestionList()
        } else {
          sltContent.value = {};
        }
      } else {
        sltCatalog = {};
      }
      pdIsAddCatalogContent();
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取数据异常', VxeNotifyType.error);
    });
}

function saveCatalog(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: catalogForm.id,
      knowledgeId: catalogForm.knowledgeId,
      pid: catalogForm.pid,
      name: catalogForm.name,
      code: catalogForm.code,
      seq: catalogForm.seq,
      status: catalogForm.status,
      orgId: !isEmpty(catalogForm.orgId) ? catalogForm.orgId : store.userInfo.orgId
    };
    let url = '';
    // 判断添加和编辑接口
    if (catalogForm.id) {
      url = '/api/wk/wkKnowledgeCatalog/editKnowledgeCatalog';
    } else {
      url = '/api/wk/wkKnowledgeCatalog/addKnowledgeCatalog';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (catalogForm.id) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
          findKnowledgeCatalogAndContentTree(res.data.id);
          showCatalogDialog.value = false;
          // 清空表单
          clearCatalogForm();
        } else {
          if (catalogForm.id) {
            VxeMessage('修改失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

function saveContent(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: contentForm.id,
      knowledgeId: contentForm.knowledgeId,
      catalogId: contentForm.catalogId,
      title: contentForm.title,
      tempContent: contentForm.tempContent,
      seq: contentForm.seq,
      status: contentForm.status,
      publishTime: contentForm.publishTime,
      orgId: !isEmpty(contentForm.orgId) ? contentForm.orgId : store.userInfo.orgId
    };
    let url = '';
    // 判断添加和编辑接口
    if (contentForm.id) {
      url = '/api/wk/wkKnowledgeContent/editKnowledgeContent';
    } else {
      url = '/api/wk/wkKnowledgeContent/addKnowledgeContent';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (contentForm.id) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
          showContentDialog.value = false;
          findKnowledgeCatalogAndContentTree(res.data.id);
          clearContentForm();
        } else {
          if (contentForm.id) {
            VxeMessage('修改失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

function appendCatalogOrContent(row: any) {
  if (row.level < maxLevel) {
    if (row.knType == 'knowledge') {
      addRootCatalogDialog(row);
    } else if (row.knType == 'catalog') {
      appendCatalog(row);
    }
  } else {
    addContentDialog(row);
  }
}
function addCatalogDialog() {
  if (sltCatalog.knType == 'knowledge') {
    addRootCatalogDialog(sltCatalog);
  } else if (sltCatalog.knType == 'catalog') {
    appendCatalog(sltCatalog);
  }
}
function addRootCatalogDialog(row: any) {
  catalogForm.pid = 0;
  catalogForm.name = '';
  catalogForm.code = '';
  catalogForm.knowledgeId = sltknowledge.id;
  catalogForm.orgId = store.userInfo.orgId;
  pnameShow.value = false;
  if (row.children.length > 0) {
    // 根分类的顺序号
    const seq = row.children[row.children.length - 1].seq + 1;
    catalogForm.seq = seq;
  } else {
    catalogForm.seq = 0;
  }
  showCatalogDialog.value = true;
}

function appendCatalog(row: any) {
  catalogForm.pname = row.name;
  catalogForm.pid = row.id;
  catalogForm.knowledgeId = sltknowledge.id;
  catalogForm.orgId = store.userInfo.orgId;
  catalogForm.name = '';
  catalogForm.code = '';
  if (row.children.length > 0) {
    const seq = row.children[row.children.length - 1].seq + 1;
    catalogForm.seq = seq;
  } else {
    catalogForm.seq = 1;
  }
  pnameShow.value = true;
  showCatalogDialog.value = true;
}

function addCatalogContentDialog() {
  if (sltCatalog.knType == 'catalog') {
    addContentDialog(sltCatalog);
  }
}

function addContentDialog(row: any) {
  contentForm.knowledgeId = sltknowledge.id;
  contentForm.catalogId = row.id;
  contentForm.orgId = store.userInfo.orgId;
  contentForm.title = '';
  contentForm.content = '';
  contentForm.tempContent = '';
  contentForm.status = 0;
  contentForm.publishTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  if (row.children.length > 0) {
    const seq = row.children[row.children.length - 1].seq + 1;
    contentForm.seq = seq;
  } else {
    contentForm.seq = 1;
  }
  showContentDialog.value = true;
}

function editCatalogOrContent(item: any, node: any) {
  if (item.knType == 'catalog') {
    editCatalogDialog(item, node);
  } else if (item.knType == 'content') {
    editContentDialog(item, node);
  }
}
function editCatalogDialog(item: any, node: any) {
  catalogForm.pid = item.pid;
  catalogForm.pname = node.parent.data.name;
  catalogForm.knowledgeId = item.knowledgeId;
  catalogForm.id = item.id;
  catalogForm.name = item.name;
  catalogForm.code = item.code;
  catalogForm.seq = item.seq;
  catalogForm.status = item.status;
  if (item.pid == 0) {
    pnameShow.value = false;
  } else {
    pnameShow.value = true;
  }
  showCatalogDialog.value = true;
}

function editContentDialog(item: any, node: any) {
  contentForm.id = item.id;
  contentForm.knowledgeId = item.knowledgeId;
  contentForm.catalogId = item.catalogId;
  contentForm.title = item.title;
  contentForm.content = item.content;
  contentForm.tempContent = item.tempContent;
  contentForm.orgId = item.orgId;
  contentForm.publishTime = item.publishTime;
  contentForm.seq = item.seq;
  contentForm.status = item.status;
  showContentDialog.value = true;
}
function editTempContentDialog(item: any) {
  contentForm.id = item.id;
  contentForm.tempContent = item.tempContent;
  contentForm.title = item.title;
  proxy.$nextTick(() => {
    const temp: any = proxy.$refs['refTempContentCkEditor'];
    if (isEmpty(item.tempContent)) {
      temp.setValue('');
    } else {
      temp.setValue(item.tempContent);
    }
  });
  showTempContentDialog.value = true;
}

function removeCatalogOrContent(row: any) {
  if (row.knType == 'catalog') {
    removeCatalog(row);
  } else if (row.knType == 'content') {
    deleteContent(row);
  }
}

function removeCatalog(row: any) {
  proxy
    .$confirm('确定删除此目录？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/wk/wkKnowledgeCatalog/deletKnowledgeCatalog';
      if (row.id) {
        if (row.children.length === 0) {
          proxy.$http
            .post(url, row)
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                findKnowledgeCatalogAndContentTree('');
              } else {
                VxeMessage('删除失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除字典异常', VxeNotifyType.error);
            });
        } else {
          VxeMessage('该目录下存在子目录,不能删除', VxeNotifyType.error);
        }
      }
    });
}

function deleteContent(row) {
  proxy
    .$confirm('确定删除此内容？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/wk/wkKnowledgeContent/deletKnowledgeContent';
      if (row.id) {
        proxy.$http
          .post(url, row)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              findKnowledgeCatalogAndContentTree('');
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage('删除异常', VxeNotifyType.error);
          });
      }
    });
}

//点击左侧分类
function handleClickType(obj: any) {
  sltCatalog = obj;
  if (sltCatalog.knType == 'content') {
    getContentByContentId();
    KnowledgeTestsRef.value?.initPage(sltknowledge.id, sltCatalog.id, false)
    KnowledgeTestsRef.value?.findTestQuestionList()//缺少字段？// 页签获取知识库表格数据
  }else {
    sltContent.value = {};
  }
  pdIsAddCatalogContent();
}

function getContentByContentId() {
  conloading.value = true;

  if (isEmpty(sltCatalog)) {
    conloading.value = false;
    return;
  }
  const url = '/api/wk/wkKnowledgeContent/getContentByContentId';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { contentId: sltCatalog.id } })
    .then((res: any) => {
      sltContent.value = res.data;
      proxy.$nextTick(() => {
        const temp: any = proxy.$refs['refContentCkEditor'];
        if (sltContent.value.status < 10) {
          if (isEmpty(sltContent.value.tempContent)) {
            temp.setValue('');
          } else {
            temp.setValue(sltContent.value.tempContent);
          }
        } else {
          if (isEmpty(sltContent.value.content)) {
            temp.setValue('');
          } else {
            temp.setValue(sltContent.value.content);
          }
        }
      });
      if (activeName.value == 'approvalTab') {
        approvalListRef.value.initPage(sltContent.value.id);
      }
      conloading.value = false;
    })
    .catch((err: any) => {
      conloading.value = false;
      VxeMessage('获取数据异常', VxeNotifyType.error);
    });
}

function updateContent() {
  const obj = {
    id: sltContent.value.id,
    knowledgeId: sltContent.value.knowledgeId,
    catalogId: sltContent.value.catalogId,
    title: sltContent.value.title,
    tempContent: sltContent.value.tempContent,
    seq: sltContent.value.seq,
    status: sltContent.value.status,
    publishTime: sltContent.value.publishTime,
    orgId: !isEmpty(sltContent.value.orgId) ? sltContent.value.orgId : store.userInfo.orgId
  };
  const url = '/api/wk/wkKnowledgeContent/editKnowledgeContent';
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('修改成功', VxeNotifyType.success);

        showContentDialog.value = false;
        getContentByContentId();
      } else {
        VxeMessage('新增失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('保存异常', VxeNotifyType.error);
    });
}

function submitContent() {
  if (isEmpty(sltContent.value.tempContent)) {
    VxeMessage('请填写内容', VxeNotifyType.error);
    return;
  }
  proxy
    .$confirm('确定要提交？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const obj = {
        id: sltContent.value.id,
        knowledgeId: sltContent.value.knowledgeId,
        catalogId: sltContent.value.catalogId,
        title: sltContent.value.title,
        tempContent: sltContent.value.tempContent,
        seq: sltContent.value.seq,
        status: 5,
        publishTime: sltContent.value.publishTime,
        orgId: !isEmpty(sltContent.value.orgId) ? sltContent.value.orgId : store.userInfo.orgId,
        submitter: store.userInfo.id,
        classify: 'submit'
      };
      const url = '/api/wk/wkKnowledgeContent/submitKnowledgeContent';
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
            showContentDialog.value = false;
            getContentByContentId();
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('保存异常', VxeNotifyType.error);
        });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function submitTempContent(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    if (isEmpty(contentForm.tempContent)) {
      VxeMessage('请填写内容', VxeNotifyType.error);
      return;
    }

    proxy
      .$confirm('确定要提交？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const obj = {
          id: contentForm.id,
          submitter: store.userInfo.id,
          orgId: !isEmpty(contentForm.orgId) ? contentForm.orgId : store.userInfo.orgId,
          title: contentForm.title,
          tempContent: contentForm.tempContent,
          status: 15,
          classify: 'edit'
        };
        const url = '/api/wk/wkKnowledgeContent/submitKnowledgeContent';
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('修改成功', VxeNotifyType.success);
              showTempContentDialog.value = false;
              getContentByContentId();
            } else {
              VxeMessage('修改失败', VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage('保存异常', VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  });
}

function handleAddIssue() {
  issueForm.id = '';
  issueForm.knowledgeId = sltknowledge.id;
  issueForm.catalogId = sltContent.value.catalogId;
  issueForm.contentId = sltContent.value.id;
  issueForm.orgId = store.userInfo.orgId;
  issueForm.title = '';
  issueForm.solution = '';
  issueForm.seq = 1;
  issueForm.status = 0;
  issueForm.publishTime = '';
  showIssueDialog.value = true;
}

async function handleEditIssue(issue, iIdx) {
  issueForm.id = issue.id;
  issueForm.title = issue.title;
  issueForm.knowledgeId = issue.knowledgeId;
  issueForm.catalogId = issue.catalogId;
  issueForm.contentId = issue.contentId;
  issueForm.solution = issue.solution;
  issueForm.issueIdx = iIdx;
  showIssueDialog.value = true;
  proxy.$nextTick(() => {
    const temp: any = proxy.$refs['refIssueEditor'];
    if (issueForm.solution) {
      temp.setValue(issueForm.solution);
    }
  });
}

function confirmIssueForm(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: issueForm.id,
      knowledgeId: issueForm.knowledgeId,
      catalogId: issueForm.catalogId,
      contentId: issueForm.contentId,
      orgId: !isEmpty(issueForm.orgId) ? issueForm.orgId : store.userInfo.orgId,
      title: issueForm.title,
      solution: issueForm.solution,
      seq: issueForm.seq,
      status: issueForm.status,
      publishTime: issueForm.publishTime
    };
    let url = '';
    // 判断添加和编辑接口
    if (issueForm.id) {
      url = '/api/wk/wkKnowledgeIssue/editKnowledgeIssue';
    } else {
      url = '/api/wk/wkKnowledgeIssue/addKnowledgeIssue';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (!issueForm.id && res.data.id) {
            issueForm.id = res.data.id;
            sltContent.value.wkKnowledgeIssueList.push(res.data);
          } else {
            sltContent.value.wkKnowledgeIssueList[issueForm.issueIdx].title = issueForm.title;
            sltContent.value.wkKnowledgeIssueList[issueForm.issueIdx].solution = issueForm.solution;
          }
          showIssueDialog.value = false;
          const temp: any = proxy.$refs['refIssueEditor'];
          temp.setValue('');
          // 清空表单
          clearIssueForm();
        } else {
          if (issueForm.id) {
            VxeMessage('修改失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
        console.log(err);
      });
  });
}

function handleDeleteIssue(issueId, idx, issues) {
  proxy
    .$confirm('确定删除此问题?', '提示', {
      cancelButtonClass: 'cancelbutton',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      isLoading.value = true;
      const url = '/api/wk/wkKnowledgeIssue/deletKnowledgeIssue';
      const obj = {
        id: issueId
      };
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除问题成功！', VxeNotifyType.success);
            issues.splice(idx, 1);
          } else {
            VxeMessage('删除问题失败', VxeNotifyType.error);
          }
          isLoading.value = false;
        })
        .catch((err) => {
          VxeMessage('删除问题错误', VxeNotifyType.error);
          isLoading.value = false;
        });
    })
    .catch((err) => {
      console.log(err);
    });
}

function getChildren(obj: any, sltId: any) {
  const children = obj.children;
  if (children.length > 0) {
    const oobj = children.find((c) => c.id == sltId);
    if (isEmpty(oobj)) {
      return getChildren(children[0], sltId);
    } else {
      return oobj;
    }
  } else {
    return obj;
  }
}

function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

function closeCatalogDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearCatalogForm();
  pnameShow.value = false;
  showCatalogDialog.value = false;
}

function closeTempContentDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearContentForm();
  showTempContentDialog.value = false;
}

function closeContentDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearContentForm();
  showContentDialog.value = false;
}
function closeIssueDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearIssueForm();
  showIssueDialog.value = false;
}
function clearCatalogForm() {
  catalogForm.id = null;
  catalogForm.knowledgeId = null;
  catalogForm.pid = null;
  catalogForm.pname = '';
  catalogForm.code = '';
  catalogForm.name = '';
  catalogForm.orgId = '';
  catalogForm.seq = 1;
  catalogForm.status = true;
}
function clearContentForm() {
  contentForm.idx = null;
  contentForm.id = null;
  contentForm.knowledgeId = null;
  contentForm.catalogId = null;
  contentForm.title = '';
  contentForm.content = '';
  contentForm.tempContent = '';
  contentForm.orgId = '';
  contentForm.publishTime = '';
  contentForm.seq = 1;
  contentForm.status = 0;
}

function clearIssueForm() {
  issueForm.id = null;
  issueForm.knowledgeId = null;
  issueForm.catalogId = null;
  issueForm.contentId = null;
  issueForm.title = '';
  issueForm.solution = '';
  issueForm.orgId = '';
  issueForm.publishTime = '';
  issueForm.seq = 1;
  issueForm.status = 0;
}
function titleCatalog() {
  if (catalogForm.id) {
    return `编辑目录`;
  } else if (!catalogForm.id) {
    return `新建目录`;
  }
}
function titleContent() {
  if (contentForm.id) {
    return `编辑`;
  } else if (!contentForm.id) {
    return `新建`;
  }
}

function pdIsAddCatalogContent() {
  if (isEmpty(sltCatalog)) {
    isAddCatalogFlag.value = true;
    isAddContentFlag.value = true;
  } else {
    if (sltCatalog.knType == 'content') {
      isAddCatalogFlag.value = true;
      isAddContentFlag.value = true;
    } else {
      if (sltCatalog.level < maxLevel) {
        isAddCatalogFlag.value = false;
        isAddContentFlag.value = true;
      } else {
        isAddCatalogFlag.value = true;
        isAddContentFlag.value = false;
      }
    }
  }
}

function getContentStatusDesc(row: any) {
  if (row.status == 0) {
    return '暂存';
  } else if (row.status == 1 || row.status == 11) {
    return '审批未通过';
  } else if (row.status == 5 || row.status == 15) {
    return '审核中';
  } else if (row.status == 10 || row.status == 20) {
    return '已审核';
  }
}


function tabHandleClick(tab) {
  if (tab.index == 1) {
    // 修改记录页签
    approvalListRef.value.initPage(sltContent.value.id);
  }else if(tab.index == 2){
    // 知识库试题页签
    // 使用类型断言调用子组件方法
    KnowledgeTestsRef.value?.findTestQuestionList(); // 获取知识库表格数据
    KnowledgeTestsRef.value?.getQuestionType(); // 获取题目类型选项
  }
}

// const inputVisible = ref(false)

</script>

<style lang="scss" scoped>
#knowCatalogManageDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  // 最左侧字典分类的树
  .sampleType {
    .tools-tree {
      min-width: 168px;
      padding: 0 5px 5px 5px;
      font-size: $font-size;
      border: none;
      .cirBtn {
        display: none;
        width: 16px;
        height: 16px;
        padding: 0px;
        margin-left: 10px;
      }
      .el-tree-node__content:hover {
        .cirBtn {
          display: inline-block !important;
        }
      }
    }
  }
  // 右侧富文本编辑器区域
  .cardBox {
    height: 100%;

    // :deep(.el-scrollbar__view) {
    //   height: calc(100% - 24px);

      .item-interval {
        padding: 0 10px 0 0;
        height: 100%;
        // 暂存和发布按钮
        .save-footer {
          display: flex;
          align-items: center;
          justify-content: flex-end; //兼容360极速浏览器在最右侧显示
          margin-right: 10px;
        }

        //显示两个按钮剩余tabs高度
        .showTwoButtonTabs {
          height: calc(100% - 48px - 341px - 14px);
          .el-tab-pane {
            height: 100%;
            .tabTableBox {
            height: 100%;
          }
          }
        }
        //不显示两个按钮剩余tabs高度
        .alreadySubmitTabs {
          height: calc(100% - 48px - 341px);
          .el-tab-pane {
            height: 100%;
            .tabTableBox {
            height: 100%;
          }
          }
        }

      }
    // }
  }
}
</style>
